<template>
  <section class="component origanize-tree">
    <div>
      <origanize-node v-for="item of dataTree" v-if="item" :key="item.id" :data="item"></origanize-node>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Mutation, Getter, namespace } from "vuex-class";
import OriganizeNode from "~/components/system-manage/department-user-manage/origanize-node.vue";
import { Emit, Prop, Watch } from "vue-property-decorator";
const systemManageModule = namespace("system-manage");

@Component({
  components: {
    OriganizeNode
  }
})
export default class OriganizeTree extends Vue {
  @Prop({ default: [] }) dataList: Array<any>;// 数据列表
  @Prop({ default: true }) isIcon: Boolean; // 数据列表

  private dataTree: Array<any> = []; // 数据树
  private selectDepartmentNode: any = {}; // 当前选择的节点（当前选择的机构）

  @Watch("dataList", { immediate: true })
  createTree(data) {
    // 过滤父节点
    let rootList = data.filter(x => {
      if (!x.deptPid) {
        return true;
      }
      return !data.find(item => item.id === x.deptPid);
    });

    // 递归构建组织树
    let fun = id => {
      // 递归对象子元素
      let list = data.filter(x => x.deptPid === id).map(row => {
        let node = Object.assign({}, row);
        // 递归构建子节点
        let children = fun(node.id);
        // 添加icon标识
        // 节点添加children或leaf属性
        if (children && children.length) {
          // 设置子元素
          node.children = children;
          // 添加叶子节点标识
          node.isLeaf = false;
          // 添加默认展开标识
          node.expand = true;
        } else {
          // 添加叶子节点标识
          node.isLeaf = true;
        }
        return node;
      });

      return list;
    };

    // 生成数据树
    this.dataTree = fun((rootList[0] || {}).deptPid);
  }

  created() {
    this.updateDefaultSelected();
  }

  /**
   * 更新默认选中节点
   */
  updateDefaultSelected() {
    if (this.dataTree && this.dataTree.length) {
      this.updateSelected(this.dataTree[0]);
    }
  }

  /**
   * 更新当前选择项
   */
  updateSelected(value) {
    if (this.selectDepartmentNode !== value) {
      this.selectDepartmentNode = value;
      // 发送change事件
      this.$emit("change", value);
    }
  }
}
</script>
<!-- Add "scoped " attribute to limit CSS to this component only -->
<style scoped>
</style>
